package com.wuchengdong.web.config;

import com.wuchengdong.web.interceptor.AuthorizationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    // 这段代码用于配置 Spring 的跨域访问，允许所有来源访问，并指定缓存时间为 3600 秒
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        WebMvcConfigurer.super.addCorsMappings(registry);
        registry.addMapping("/**")
                .allowedOriginPatterns("*") // 允许所有来源访问
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS") // 允许使用的方法
                .allowCredentials(true) // 允许发送 Cookie
                .maxAge(3600) // 缓存时间为 3600 秒
                .allowedHeaders("*");
    }

    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(authorizationInterceptor)
                .addPathPatterns("/api/**");
    }
}
